<script lang="ts" setup>
import type { LedgerRecycleItem } from './data';

import type {
  OnActionClickParams,
  VxeTableGridOptions,
} from '#/adapter/vxe-table';

import { Page } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  getLedgerRecycleList,
  permanentDeleteLedger,
  restoreLedger,
} from '#/api/system/ledger-recycle';

import { useColumns } from './data';

/**
 * 恢复账簿
 */
function onRestore(row: LedgerRecycleItem) {
  const hideLoading = message.loading({
    content: `正在恢复账簿 ${row.ledgerName}...`,
    duration: 0,
    key: 'action_process_msg',
  });
  restoreLedger(row.id)
    .then(() => {
      message.success({
        content: `账簿 ${row.ledgerName} 恢复成功`,
        key: 'action_process_msg',
      });
      refreshGrid();
    })
    .catch(() => {
      hideLoading();
    });
}

/**
 * 彻底删除账簿
 */
function onPermanentDelete(row: LedgerRecycleItem) {
  const hideLoading = message.loading({
    content: `正在彻底删除账簿 ${row.ledgerName}...`,
    duration: 0,
    key: 'action_process_msg',
  });
  permanentDeleteLedger(row.id)
    .then(() => {
      message.success({
        content: `账簿 ${row.ledgerName} 已彻底删除`,
        key: 'action_process_msg',
      });
      refreshGrid();
    })
    .catch(() => {
      hideLoading();
    });
}

/**
 * 表格操作按钮的回调函数
 */
function onActionClick({ code, row }: OnActionClickParams<LedgerRecycleItem>) {
  switch (code) {
    case 'delete': {
      onPermanentDelete(row);
      break;
    }
    case 'restore': {
      onRestore(row);
      break;
    }
  }
}

const [Grid, gridApi] = useVbenVxeGrid({
  gridEvents: {},
  gridOptions: {
    columns: useColumns(onActionClick),
    height: 'auto',
    keepSource: true,
    pagerConfig: {
      enabled: true,
      pageSize: 20,
      pageSizes: [10, 20, 50, 100],
    },
    proxyConfig: {
      ajax: {
        query: async (params) => {
          const { page } = params;
          return await getLedgerRecycleList({
            page: page.currentPage,
            pageSize: page.pageSize,
          });
        },
      },
    },
    toolbarConfig: {
      custom: true,
      export: true,
      refresh: true,
      zoom: true,
    },
  } as VxeTableGridOptions,
});

/**
 * 刷新表格
 */
function refreshGrid() {
  gridApi.query();
}
</script>

<template>
  <Page auto-content-height>
    <Grid table-title="账簿回收站" />
  </Page>
</template>